package com.fm.common.net

import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.HttpStatusCodeException
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.io.IOException
import java.lang.reflect.Type

/**
 *
 * @Author:         ly2
 * @CreateDate:     2020/12/29
 * @Description:    有数据返回数据解析
 *
 */

@Parser(name = "Response")
open class ResponseParser<T> : AbstractParser<T> {

    //以下两个构造方法是必须的
    protected constructor() : super()

    @Suppress("unused")
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        val body: ResponseBody? = response.body
        if (body == null) {
            throw HttpStatusCodeException(response)
        } else {
            val resultStr = body.string()
            try {
                val type: Type = ParameterizedTypeImpl[BaseResponseEntity::class.java, mType] //获取泛型类型
                val rb = resultStr.toResponseBody()
                val rp = response.newBuilder().body(rb).build()
                val data: BaseResponseEntity<T> = rp.convert(type)   //获取Response对象
                val result = data.result                             //获取data字段
                if (data.code != "200" || null == result) { //code不等于200，说明数据不正确，抛出异常
                    throw ParseException(data.code, data.message, response)
                }
                return result
            } catch (e: Exception) {
                val jsonObj = JSONObject(resultStr)
                val code = jsonObj.optString("code")
                val message = jsonObj.optString("message")
                throw ParseException(code, message, response)
            } finally {
                body.close()
            }
        }
    }
}